package com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.service.core;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.SdwcoatencentConnection;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.utils.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public final class RequestHandleService {
  public JSONObject handlerPost(SdwcoatencentConnection connection, String secret, String url, Object bodyParams) {
    String host = connection.getHost();
    Map<String, String> headerParams = new HashMap<>();
    Map<String, Object> queryParams = new HashMap<>();
    String wechatToken = getToken(connection, secret);
    queryParams.put("access_token", wechatToken);
    Integer httpTimeOut = connection.getHttpTimeOut();
    String httpResponse = HttpClientUtils.doPost(host, url, headerParams, queryParams, bodyParams, httpTimeOut.intValue());
    return dealHttpResponse(httpResponse);
  }
  
  public JSONObject handlerGet(SdwcoatencentConnection connection, String secret, String url, Map<String, Object> paramsMap) {
    Map<String, String> headerParams = new HashMap<>();
    String wechatToken = getToken(connection, secret);
    paramsMap.put("access_token", wechatToken);
    String host = connection.getHost();
    Integer httpTimeOut = connection.getHttpTimeOut();
    String httpResponse = HttpClientUtils.doGet(host, url, headerParams, paramsMap, httpTimeOut.intValue());
    return dealHttpResponse(httpResponse);
  }
  
  private String getToken(SdwcoatencentConnection connection, String secret) {
    String host = connection.getHost();
    String corpid = connection.getCorpid();
    if (StringUtils.isBlank(secret))
      secret = StringUtils.isBlank(connection.getAppCorpsecret()) ? connection.getConnectCorpsecret() : connection.getAppCorpsecret(); 
    Integer httpTimeOut = connection.getHttpTimeOut();
   /* String wechatToken = AuthService.getToken(host, corpid, secret, httpTimeOut);
    return wechatToken;*/
    return null;
  }
  
  private JSONObject dealHttpResponse(String httpResponse) {
    JSONObject returnObject;
    if (StringUtils.isBlank(httpResponse) || !JSONUtil.isTypeJSON(httpResponse)) {
      returnObject = new JSONObject();
      returnObject.set("errcode", "999");
      returnObject.set("errmsg", httpResponse);
    } else {
      returnObject = JSONUtil.parseObj(httpResponse);
    } 
    return returnObject;
  }
}